
package com.yimixian.app.goods;

import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.CommentMessage;
import com.yimixian.app.EventBusDomain.CommentReportMessage;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.adapter.CommentAdapter;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.Banner;
import com.yimixian.app.model.Comment;
import com.yimixian.app.model.CommentReportResponse;
import com.yimixian.app.model.Comments;
import com.yimixian.app.model.GoodDetail;
import com.yimixian.app.model.ImageInfo;
import com.yimixian.app.model.PromotionInfo;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.CommentGetAPI;
import com.yimixian.app.rest.api.CommentPublishAPI;
import com.yimixian.app.rest.api.CommentReportAPI;
import com.yimixian.app.rest.api.GoodDetailAPI;
import com.yimixian.app.ui.BaseHttpFragment;
import com.yimixian.app.ui.PlusMinusIcon;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.GlobalLayoutUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.util.DensityUtils;
import com.ymx.sdk.util.DeviceUtils;
import com.ymx.sdk.widget.ListViewLoadMore.AutoLoadMoreListView;

import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;
import de.greenrobot.event.EventBus;

import org.json.JSONObject;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class GoodDetailTopFragment extends BaseHttpFragment
        implements AutoLoadMoreListView.OnLoadMoreListener, View.OnClickListener,
        AbsListView.OnScrollListener {
    public final static String IMAGE_TXT_TAB = "image_txt_tab";
    public final static String COMMENT_TAB = "comment_tab";
    public final static int RETURN_TO_CATEGORY = 1000;
    private final int mSize = 10;
    private final int mGoodDetailRequestIndex = 0;

    private AutoLoadMoreListView mAutoLoadMoreListView;
    private CommentAdapter mCommentAdapter;
    public List<Comment> mNormalList;
    public List<ImageInfo> mGoodsDetailImageTxtList;
    private String mCurrentTab;
    private TextView mImageTxtView1;
    private TextView mCommentView1;
    private TextView mRedPointTextView;
    private LinearLayout mLlBar1;
    public int mCommentPosition = 0;
    public int mImageTxtPosition = 0;
    private String mGoodId;
    private YmxDataService mYmxDataService;
    private GoodDetailAPI mGoodDetailAPI;
    private ShareGoodView mShareLayout;
    private CommentGetAPI mCommentGetAPI;
    private CommentReportAPI mCommentReportAPI;
    private CommentPublishAPI mCommentPublishAPI;
    private String mOffset = "0";
    private int mLastCount;
    private String mCommentContent = "";
    private int mTasteCount;
    private int mFreshnessCount;
    private String mCommentId = "";
    private boolean mIsShowRedPoint = false;
    public BannersView mBannersView;

    @InjectView(R.id.tv_detail_title)
    TextView mTvDetailTitle;
    @InjectView(R.id.tv_sub_title)
    TextView mTvSubTitle;
    @InjectView(R.id.tv_good_price)
    TextView mTvGoodPrice;
    @InjectView(R.id.available_text)
    TextView mAvailableText;
    @InjectView(R.id.tv_sub_start_time)
    TextView mStartTimeText;
    @InjectView(R.id.tv_good_price_old)
    TextView mOldPriceText;
    @InjectView(R.id.iv_promoteIcon)
    ImageView mPromoteIcon;
    @InjectView(R.id.tv_good_price_yuan)
    TextView mTvGoodPriceYuan;
    @InjectView(R.id.ll_banner)
    LinearLayout mLlBanner;
    @InjectView(R.id.function_text)
    TextView mFunctionText;
    @InjectView(R.id.iv_good_level)
    ImageView mIvGoodLevel;
    @InjectView(R.id.ll_cu_xiao)
    LinearLayout ll_cu_xiao;
    @InjectView(R.id.rl_cu_xiao)
    RelativeLayout rl_cu_xiao;
    @InjectView(R.id.divider_view)
    View divider_view;
//    @InjectView(R.id.iv_back)
    ImageView mIvBack;
//    @InjectView(R.id.iv_share)
    ImageView mIvShare;
//    @InjectView(R.id.rl_back_share_container)
    RelativeLayout mBackShareContainer;

    private View headerView;

    private PlusMinusIcon mPlusMinusIcon;

    private LinearLayout moreView; //查看更多

    int screenWidth;
    public GoodDetailTopFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = View.inflate(getContext(), R.layout.fragment_good_detail_comment, null);
        headerView = View.inflate(getContext(), R.layout.fragment_good_detail_top, null);
        screenWidth = DeviceUtils.getScreenWidth(getContext());
        initView(view, headerView);
        initData();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        DateUtil.setCityUMeng(null, UMengConstants.NEW_GOODDETAIL_PV);
        mAutoLoadMoreListView.addHeaderView(headerView);
        if (getActivity() != null && getContext() != null) {
            mCommentAdapter = new CommentAdapter(getContext(), getActivity(),
                    mGoodsDetailImageTxtList);
        }
        mAutoLoadMoreListView.setAdapter(mCommentAdapter);
        mAutoLoadMoreListView.setOnLoadMoreListener(this);
        mAutoLoadMoreListView.setOnScrollListener(this);

        mGoodId = getArguments().getString(GoodDetailActivity.INTENT_EXTRA_GOOD_ID);
        if (mGoodId == null && getActivity() != null) {
            UiUtils.showToast(getActivity(), "数据传递失败");
        } else {
            mGoodId = String.valueOf(mGoodId);
        }
        showDialog("加载中", false);
        initDataWithNetWork();

        return view;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mNormalList = new ArrayList<>();
        mGoodsDetailImageTxtList = new ArrayList<>();
    }

    /**
     * 网络加载数据
     */
    private void initDataWithNetWork() {
        mYmxDataService = YmxDataService.getInstance();
        String mGoodDetailRequestKey = GoodDetailAPI.GOOD_DETAIL.replace("{id}", mGoodId);
        setRequestKey(mGoodDetailRequestIndex, mGoodDetailRequestKey);
        fetchData(true, getRequestKeyByIndex(mGoodDetailRequestIndex));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mLlBanner != null) {
            mLlBanner.removeAllViews();
        }
        EventBus.getDefault().unregister(this);
    }

    /**
     * 初始化view
     */
    private void initView(View view, View headerView) {
        mAutoLoadMoreListView = (AutoLoadMoreListView) view
                .findViewById(R.id.auto_loadmore_listview);
        mImageTxtView1 = (TextView) view.findViewById(R.id.tv_image_txt1);
        mCommentView1 = (TextView) view.findViewById(R.id.tv_comment1);
        mLlBar1 = (LinearLayout) view.findViewById(R.id.ll_bar1);
        mRedPointTextView = (TextView)view.findViewById(R.id.order_point);
        mIvBack = (ImageView) view.findViewById(R.id.iv_back);
        mIvShare = (ImageView) view.findViewById(R.id.iv_share);
        mBackShareContainer = (RelativeLayout) view.findViewById(R.id.rl_back_share_container);
        ButterKnife.inject(this, headerView);

        mImageTxtView1.setOnClickListener(this);
        mCommentView1.setOnClickListener(this);
        mIvBack.setOnClickListener(this);
        mIvShare.setOnClickListener(this);
    }

    @Override
    public void onLoadMore() {
        if (COMMENT_TAB.equals(mCurrentTab) && mAutoLoadMoreListView != null) {
            if (checkNetWorkState()) {
                // 获取网络加载更多的数据
                if (mLastCount == mSize) {
                    fetchData(true, CommentGetAPI.COMMENT_GET);
                } else {
                    mAutoLoadMoreListView.onLoadMoreComplete();
                }
            } else {
                mAutoLoadMoreListView.onLoadMoreComplete();
            }
        } else {
            mAutoLoadMoreListView.onLoadMoreComplete();
        }
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        if (requestKeys != null && CommentGetAPI.COMMENT_GET.equals(requestKeys)) {
            if (!TextUtils.isEmpty(mGoodId)) {
                mCommentGetAPI = new CommentGetAPI(Integer.parseInt(mGoodId), mOffset, mSize, this);
            }
        } else if (requestKeys != null
                && CommentPublishAPI.COMMENT_PUBLISH.equals(requestKeys)) {
            if (!TextUtils.isEmpty(mGoodId)) {
                mCommentPublishAPI = new CommentPublishAPI(Integer.parseInt(mGoodId),
                        mCommentContent, mTasteCount, mFreshnessCount, this);
            }
        } else if (requestKeys != null && CommentReportAPI.COMMENT_REPORT.equals(requestKeys)) {
            mCommentReportAPI = new CommentReportAPI(mCommentId, this);
        } else {
            if (mGoodDetailAPI == null) {
                mGoodDetailAPI = new GoodDetailAPI(mGoodId, this);
            }
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        if (url.contains(getRequestKeyByIndex(mGoodDetailRequestIndex)) && mGoodDetailAPI != null) {
            GoodDetail goodDetail = mGoodDetailAPI.parseJson(responseJson);
            if(goodDetail != null) {
                SharedPreferencesHelper.saveRatingBarText1(goodDetail.tasteDesc);
                SharedPreferencesHelper.saveRatingBarText2(goodDetail.freshnessDesc);
                mIsShowRedPoint = goodDetail.canComment;
                setGoodDetailData(goodDetail);
          
                if(isAdded() && getActivity() instanceof GoodDetailActivity && ((GoodDetailActivity)getActivity()).getPrimaryFragmentGroup() != null) {
                    ((GoodDetailFragmentGroup)((GoodDetailActivity)getActivity()).getPrimaryFragmentGroup()).resetInitDetailCartFragmentPlusMinitIcon();
                }
            }
        }
        if (isAdded() && url.contains(CommentGetAPI.COMMENT_GET_COMMENTS) && mCommentGetAPI != null) {
            Comments comments = mCommentGetAPI.parseJson(responseJson);
            if (comments != null) {
                mLastCount = comments.count;
                if (comments.count == mSize) {
                    mOffset = comments.latestId;
                }
                if (mNormalList != null) {
                    mNormalList.addAll(comments.comments);
                }
                if (mImageTxtView1 != null && mCommentView1 != null&&isAdded()) {
                    mCommentView1.setTextColor(getResources().getColor(R.color.ymx_orange));
                    mImageTxtView1.setTextColor(getResources().getColor(R.color.home_black_color));
                }
                if (mCommentAdapter != null) {
                    mCommentAdapter.setCurrentTab(mCurrentTab);
                }
                notifyDataSource(mNormalList);
                if (mAutoLoadMoreListView != null) {
                    mAutoLoadMoreListView.onLoadMoreComplete();
                }
            }
        }
        if (url.contains(CommentPublishAPI.COMMENT_PUBLISH) && mCommentPublishAPI != null) {
            Comment comment = mCommentPublishAPI.parseJson(responseJson);
            if (mNormalList != null) {
                if (mCurrentTab != null && mCurrentTab.equals(COMMENT_TAB)) {
                    mNormalList.add(0, comment);
                    if (mCommentAdapter != null) {
                        mCommentAdapter.setCanComment(false);
                        mCommentAdapter.notifyDataSetChanged();
                    }
                    notifyDataSource(mNormalList);
                }
            }
            mIsShowRedPoint = false;
            UiUtils.showToast("评论成功");
        }
        if (url.contains(CommentReportAPI.COMMENT_REPORT) && mCommentReportAPI != null) {
            CommentReportResponse reportResponse = mCommentReportAPI.parseJson(responseJson);
            if (reportResponse != null && reportResponse.code == 200) {
                UiUtils.showToast("举报成功");
            }
        }
        hideDialog();
        hidePopupWindow();
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        hideDialog();
        hidePopupWindow();
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
        if (key.equals(getRequestKeyByIndex(mGoodDetailRequestIndex))) {
            if (mGoodDetailAPI != null) {
                mGoodDetailAPI.getGoodDetail();
            }
        }
        if (CommentGetAPI.COMMENT_GET.equals(key)) {
            if (mCommentGetAPI != null) {
                mCommentGetAPI.commentGet();
            }
            if (isAdded()) {
                showPopupWindow(getActivity(), R.id.popupwindow_container);
            }
        }
        if (CommentPublishAPI.COMMENT_PUBLISH.equals(key)) {
            if (mCommentPublishAPI != null) {
                mCommentPublishAPI.commentPublish();
            }
            if (isAdded()) {
                showPopupWindow(getActivity(), R.id.popupwindow_container);
            }
        }
        if (CommentReportAPI.COMMENT_REPORT.equals(key)) {
            if (mCommentReportAPI != null) {
                mCommentReportAPI.commentReport();
            }
            if (isAdded()) {
                showPopupWindow(getActivity(), R.id.popupwindow_container);
            }
        }

    }

    public void setGoodDetailData(GoodDetail goodDetail) {
        if (goodDetail != null) {
            initViewWithData(goodDetail);
            if (mIvShare != null) {
                mIvShare.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 初始化页面布局数据
     *
     * @param goodDetail 数据源
     */
    public void initViewWithData(GoodDetail goodDetail) {
        hideDialog();
        Good good = goodDetail.good;
        if (goodDetail.good.imgUrl.size() == 0) {
            mLlBanner.setVisibility(View.GONE);
        } else {
            addBannerView(good.imgUrl);
            mLlBanner.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.title)) {
            mTvDetailTitle.setVisibility(View.GONE);
        } else {
            mTvDetailTitle.setText(Strings.ToSBC(good.title));
            mTvDetailTitle.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.unitDesc) && TextUtils.isEmpty(good.productby)) {
            mTvSubTitle.setVisibility(View.GONE);
        } else {
            if (TextUtils.isEmpty(good.productby) || "null".equals(good.productby)) {
                mTvSubTitle.setText(good.unitDesc);
            } else {
                mTvSubTitle.setText(good.unitDesc + "   " + "产地：" + good.productby);
            }
            mTvSubTitle.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.unitPrice)) {
            mTvGoodPrice.setVisibility(View.GONE);
        } else {
            mTvGoodPrice.setText(good.unitPrice);
            mTvGoodPriceYuan.setVisibility(View.VISIBLE);
            mTvGoodPrice.setVisibility(View.VISIBLE);
        }
        mOldPriceText.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        if (TextUtils.isEmpty(good.unitOldPrice)) {
            mOldPriceText.setVisibility(View.GONE);
        } else {
            mOldPriceText.setText("¥" + good.unitOldPrice);
            mOldPriceText.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.stockCount)) {
            mAvailableText.setVisibility(View.GONE);
        } else {
            mAvailableText.setText(good.stockCount);
            mAvailableText.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.saleStatus)) {
            mStartTimeText.setVisibility(View.GONE);
        } else {
            mStartTimeText.setText(good.saleStatus);
            mStartTimeText.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.newPromoteType)) {
            mPromoteIcon.setVisibility(View.INVISIBLE);
        } else {
            Display display = (getActivity()).getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            if (isAdded()) {
                float sizePromotion = getResources().getDimension(R.dimen.jiao_biao_size);
                Picasso.with(getActivity())
                        .load(DataManager.getInstance().getImageUrl(good.newPromoteType,
                            (int)sizePromotion))
                        .into(mPromoteIcon);
            }
        }
        
        if (TextUtils.isEmpty(goodDetail.getGood().getFuntionDesc())){
            mFunctionText.setVisibility(View.GONE);
        }else {
            mFunctionText.setVisibility(View.VISIBLE);
            mFunctionText.setText(goodDetail.getGood().getFuntionDesc());
        }
        switch (goodDetail.getGood().getGoodsLevel()){   
            case 0:
                mIvGoodLevel.setVisibility(View.GONE);
                break;
            case 1:
                mIvGoodLevel.setImageResource(R.drawable.good_level_1);
                break;
            case 2:
                mIvGoodLevel.setImageResource(R.drawable.good_level_2);
                break;
            case 3:
                mIvGoodLevel.setImageResource(R.drawable.good_level_3);
                break;
            case 4:
                mIvGoodLevel.setImageResource(R.drawable.good_level_4);
                break;
            case 5:
                mIvGoodLevel.setImageResource(R.drawable.good_level_0);
                break;
            
        }

        divider_view.setVisibility(View.VISIBLE);
        final ArrayList<PromotionInfo> infos = good.mGoodsItem.promotionInfos;
        float density = getResources().getDisplayMetrics().density;
        if(infos != null && infos.size() > 0){
            ll_cu_xiao.setVisibility(View.VISIBLE);
            for (int i = 0; i < infos.size(); i++) {
                if(i == 3){
                    //页面只显示三条
                    break;
                }
                final PromotionInfo info = infos.get(i);
                RelativeLayout rl_row = new RelativeLayout(getContext());
                rl_row.setBackgroundResource(R.drawable.item_white_selector);

                TextView tv_title = new TextView(getContext());
                tv_title.setId(R.id.title_text);
                tv_title.setText(info.title);
                tv_title.setTextColor(getResources().getColor(R.color.ymx_orange));
                tv_title.setBackgroundResource(R.drawable.te_hui_back);
                tv_title.setTextSize(13);
                tv_title.setPadding((int) (2 * density), (int) (2 * density), (int) (2 * density), (int) (2 * density));
                RelativeLayout.LayoutParams lp_title = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                lp_title.addRule(RelativeLayout.CENTER_VERTICAL);

                TextView tv_desc = new TextView(getContext());
                tv_desc.setText(info.desc);
                tv_desc.setTextColor(0xff292929);
                tv_desc.setTextSize(13);
                tv_desc.setPadding((int) (7 * density), 0, 0, 0);
                tv_desc.setSingleLine(true);
                tv_desc.setEllipsize(TextUtils.TruncateAt.END);
                tv_desc.setEms(15);
                RelativeLayout.LayoutParams lp_desc = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                lp_desc.addRule(RelativeLayout.CENTER_VERTICAL);
                lp_desc.addRule(RelativeLayout.RIGHT_OF, R.id.title_text);

                rl_row.addView(tv_title, lp_title);
                rl_row.addView(tv_desc, lp_desc);

                if(i == 0 && infos.size() >= 3){
                    ImageView iv_more = new ImageView(getContext());
                    iv_more.setImageResource(R.drawable.icon_te_hui_more);
                    moreView = new LinearLayout(getContext());
                    moreView.setPadding((int) (20 * density), 0, (int) (20 * density), 0);
                    RelativeLayout.LayoutParams lp_more = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                    lp_more.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    lp_more.setMargins(0, (int) (20 * density), 0, 0);
                    moreView.setPadding((int) (20 * density), (int) (20 * density), (int) (20 * density), (int) (20 * density));
                    moreView.addView(iv_more);
                    rl_cu_xiao.addView(moreView, lp_more);
                    moreView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            moreView.setEnabled(false);
                            UiUtils.showEffectDialog(getContext(), 0, infos);
                            if (mBannersView != null && mBannersView.getBannersView() != null) {
                                mBannersView.getBannersView().stopAutoScroll();
                            }
                        }
                    });
                }

                LinearLayout.LayoutParams lp_row = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                rl_row.setPadding(0, (int) (5 * density), 0, (int) (5 * density));
                if(!Strings.isNullOrEmpty(info.url))
                    rl_row.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getContext(), WebViewActivity.class);
                            intent.putExtra(WebViewActivity.EXTRA_URL, info.url);
                            startActivity(intent);
                        }
                    });

                ll_cu_xiao.addView(rl_row, lp_row);
            }

            ll_cu_xiao.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ll_cu_xiao.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    View view = ((GoodDetailActivity) getActivity()).mCommentGuildView;
                    if(view != null){
                        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();
                        lp.topMargin += ll_cu_xiao.getHeight();
                        view.requestLayout();
                        view.setVisibility(View.VISIBLE);
                    }
                }
            });

        }else{
            View view = ((GoodDetailActivity) getActivity()).mCommentGuildView;
            if(view != null){
                view.setVisibility(View.VISIBLE);
            }
        }

        // 设置图文详情页面数据
        mGoodsDetailImageTxtList = good.mImageInfos;
        notifyDataSource(mGoodsDetailImageTxtList);
        if (mCommentAdapter != null) {
            mCommentAdapter.setCanComment(goodDetail.canComment);
            mCommentAdapter.setCommentShow(goodDetail.commentShow);
            mCommentAdapter.setBtnName(goodDetail.commentBtnName);
        }
        // 绑定分享页面
        if(isAdded() && getActivity() instanceof GoodDetailActivity) {
            mShareLayout = ((GoodDetailActivity)getActivity()).mShareLayout;
            if(mShareLayout != null) {
                mShareLayout.bind(goodDetail.share.title, goodDetail.share.shareurl,
                    goodDetail.share.iconImgurl, goodDetail.share.shareContent);
            }
        }
        // CartManager.getInstance().sendQuantityChangeBroadCast();
    }

    public void addBannerView(final List<String> imgUrl) {
        if (isAdded()) {
            mBannersView = new BannersView(getActivity());
            final List<Banner> banners = new ArrayList<>();
            for (String url : imgUrl) {
                banners.add(new Banner(url, null));
            }

            GlobalLayoutUtils.runAfterLayout(mBannersView, new Runnable() {
                @Override
                public void run() {
                    mBannersView.bind(banners);
                }
            });
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    (int)(DensityUtils.dp2px(SystemFramework.getInstance().getGlobalContext(),244))
            );
            mLlBanner.addView(mBannersView, params);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(moreView != null)
            moreView.setEnabled(true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_image_txt1:
                mCurrentTab = IMAGE_TXT_TAB;
                if (mImageTxtView1 != null && mCommentView1 != null) {
                    setImageTxtIconShow();
                }
                if (mCommentAdapter != null) {
                    mCommentAdapter.setCurrentTab(mCurrentTab);
                }
                notifyDataSource(mGoodsDetailImageTxtList);
                break;
            case R.id.tv_comment1:
                mCurrentTab = COMMENT_TAB;
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                    UMengConstants.NEW_GOODDETAIL_COMMENTBTN);
                if(mCommentView1 != null && mImageTxtView1 != null) {
                    setCommentIconShow();
                }
                if (mNormalList.size() == 0) {
                    fetchData(true, CommentGetAPI.COMMENT_GET);
                } else {
                    if (mCommentAdapter != null) {
                        mCommentAdapter.setCurrentTab(mCurrentTab);
                    }
                    notifyDataSource(mNormalList);
                    if (mAutoLoadMoreListView != null) {
                        mAutoLoadMoreListView.onLoadMoreComplete();
                    }
                }
                break;
            case R.id.iv_back:
                if (isAdded()) {
                    getActivity().finish();
                }
                break;
            case R.id.iv_share:
                if(mShareLayout == null) {
                    mShareLayout = getShareGoodView();
                }
                if (mShareLayout != null && mShareLayout.getVisibility() == View.GONE) {
                    if(isAdded() && getActivity() instanceof GoodDetailActivity) {
                        ((GoodDetailActivity)getActivity()).startMasking();
                    }
                    mShareLayout.openShareViewWithAnim();
                }
                break;
        }
    }

    /**
     * 更新数据源
     * 
     * @param list 数据源
     */
    private void notifyDataSource(List list) {
        if (list == null) {
            return;
        }
        if (mCommentAdapter != null && mCommentAdapter.mCommentList != null
                && mAutoLoadMoreListView != null) {
            mCommentAdapter.mCommentList.clear();
            mCommentAdapter.mCommentList.addAll(list);
            mCommentAdapter.notifyDataSetChanged();

            if (COMMENT_TAB.equals(mCurrentTab)) {
                if (mCommentPosition != 0) {
                    mAutoLoadMoreListView.setSelection(mCommentPosition);
                }
            } else {
                if (mImageTxtPosition != 0) {
                    mAutoLoadMoreListView.setSelection(mImageTxtPosition);
                }
            }
        } else {
            if (getActivity() != null) {
                mCommentAdapter = new CommentAdapter(getContext(), getActivity(), list);
            }
            if (mAutoLoadMoreListView != null) {
                mAutoLoadMoreListView.setAdapter(mCommentAdapter);
            }
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {
        if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == i) {
            if (COMMENT_TAB.equals(mCurrentTab)) {
                mCommentPosition = absListView.getFirstVisiblePosition();
            } else {
                mImageTxtPosition = absListView.getFirstVisiblePosition();
            }
        }

    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {
        if (mLlBar1 != null) {
            if (i != 0) {
                mLlBar1.setVisibility(View.VISIBLE);
                if(mIsShowRedPoint && mRedPointTextView != null) {
                    mRedPointTextView.setVisibility(View.VISIBLE);
                }
            } else {
                mLlBar1.setVisibility(View.GONE);
                if(mRedPointTextView != null) {
                    mRedPointTextView.setVisibility(View.GONE);
                }
            }
        }
    }

    public ShareGoodView getShareGoodView() {
        if (mShareLayout != null) {
            return mShareLayout;
        } else if (isAdded() && getActivity() instanceof GoodDetailActivity) {
            return ((GoodDetailActivity)getActivity()).mShareLayout;
        } else {
            return null;
        }
    }

    public void onEventMainThread(String message) {
        if (message != null) {
            if (Constants.EVENT_BUS_GOODS_DETAIL_COMMENT.equals(message)) {
                mCurrentTab = COMMENT_TAB;
                if (mNormalList.size() == 0) {
                    fetchData(true, CommentGetAPI.COMMENT_GET);
                } else {
                    if (mCommentAdapter != null) {
                        mCommentAdapter.setCurrentTab(mCurrentTab);
                    }
                    notifyDataSource(mNormalList);
                }
                if (mImageTxtView1 != null && mCommentView1 != null) {
                    setCommentIconShow();
                }
            } else if (Constants.EVENT_BUS_GOODS_DETAIL_IMAGE.equals(message)) {
                mCurrentTab = IMAGE_TXT_TAB;
                if (mImageTxtView1 != null && mCommentView1 != null) {
                    setImageTxtIconShow();
                }
                if (mCommentAdapter != null) {
                    mCommentAdapter.setCurrentTab(mCurrentTab);
                }
                notifyDataSource(mGoodsDetailImageTxtList);
            } else if (Constants.EVENT_BUS_COMMENT_REPORT.equals(message)) {
                fetchData(true, CommentReportAPI.COMMENT_REPORT);
            } else if (Constants.EVENT_BUS_DISSMISS_DIALOG.equals(message)) {
                hideDialog();
                hidePopupWindow();
            }
        }
    }

    /**
     * 设置评论状态栏的显示
     */
    private void setCommentIconShow() {
        mCommentView1.setTextColor(getResources().getColor(R.color.ymx_orange));
        mImageTxtView1.setBackgroundColor(getResources().getColor(R.color.detail_comment_tab));
        mCommentView1.setBackgroundColor(getResources().getColor(R.color.white));
        mImageTxtView1.setTextColor(getResources().getColor(R.color.home_black_color));
    }

    /**
     * 设置图文详情状态栏的显示
     */
    private void setImageTxtIconShow() {
        mImageTxtView1.setTextColor(getResources().getColor(R.color.ymx_orange));
        mCommentView1.setBackgroundColor(getResources().getColor(R.color.detail_comment_tab));
        mImageTxtView1.setBackgroundColor(getResources().getColor(R.color.white));
        mCommentView1.setTextColor(getResources().getColor(R.color.home_black_color));
    }

    public void onEventMainThread(CommentMessage message) {
        if (message != null) {
            mCommentContent = message.comment;
            mTasteCount = message.taste;
            mFreshnessCount = message.freshness;
            fetchData(true, CommentPublishAPI.COMMENT_PUBLISH);
        }
    }

    public void onEventMainThread(CommentReportMessage message) {
        if (message != null) {
            mCommentId = message.commentId;
            fetchData(true, CommentReportAPI.COMMENT_REPORT);
        }
    }

    public void setmPlusMinusIcon(PlusMinusIcon mPlusMinusIcon) {
        this.mPlusMinusIcon = mPlusMinusIcon;
    }

    public PlusMinusIcon getmPlusMinusIcon() {
        return mPlusMinusIcon;
    }
}
